import React, { Component } from 'react';
import { GLOBAL } from '../../../config/global';
import {
  StyleSheet,
  Text,
  View,
  Image,
  TouchableOpacity,
  PixelRatio,
  FlatList,
  Alert,
  TextInput,
} from "react-native";
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import ToastUtil from '../../../utils/toast';
import HTTP from '../../../utils/http';
import { API, API_GENERATE } from '../../../config/api';
import { NavigationEvents } from 'react-navigation';
import { RefuseModal } from '../../../component/ModalVerifylComponent.js';
import Permission from '../../../utils/permission';
import { Button } from '../../../components/form/button';
import { CURRENCY } from '../../../utils/helper';



const scale = GLOBAL.SCALE;
const checkOn = require('../../../imgs/checkOn.png');
const checkOff = require('../../../imgs/checkOff.png');

/** 
 * titleName: '' // 顶部标题名
 * isQh: true/false // 是否是泉化
 * longFrame: {}  // 再次选择，把之前数据的传过来
 * bidId: string,  //转意向销售 用来判断
 * companyId: string,  //转意向销售 长约框架用
 * goodsId: string   //转意向销售 长约框架用
 * */

export class LongFrameListPage extends Component {
  static navigationOptions = ({ navigation, navigationOptions }) => {
    let params = navigation.state.params || {};
    return {
      title: params.titleName || '',
      headerTintColor: style.color.white,
      headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
      headerStyle: {
        elevation: 0,
        backgroundColor: style.color.themeColor,
      },
      headerTitleStyle: {
        flex: 1,
        textAlign: 'center'
      }
    }
  }

  constructor(props) {
    super(props);
    this.state = {
      status: 'data',
      listData: [],
      refreshIcon: false,
    };
    this.totalPage = 1;
    this.reload = true; // 判断是整个页面刷新还是下拉刷新
    let { isQh, longFrame, orderType, bidId, goodsId, companyId, sendData } = props.navigation.state.params || {};
    this.bidId = bidId || false;
    this.selectedFrame = longFrame || {};
    this.pageParams = {
      pageNo: 1,
      pageSize: 5,
      searchKey: '',
      isQh: isQh ? 'Y' : 'N',
      orderType,
      ...sendData,
      companyId: companyId || null
    }
    if (bidId) { //参数 转单用 代表是转单
      this.pageParams.sourceFlag = '1'
    }
  }

  async componentWillMount() {
    this.initPage();
  }

  initPage = async () => {
    this.setState({
      status: this.reload ? 'loading' : 'data',
      refreshIcon: !this.reload && this.pageParams.pageNo == '1'
    })
    let res = await HTTP.POST(API_GENERATE(API.LONG_FRAME_LIST), this.pageParams);
    if (this.pageParams.pageNo == '1') this.selectedFrame = {};
    if (res) {
      this.totalPage = res.totalPage;
      res.rows.forEach(item => {
        item.selected = this.selectedFrame.orderId == item.orderId;
      })
      this.setState({
        status: res.rows.length > 0 ? 'data' : 'empty',
        listData: this.pageParams.pageNo == '1' ? res.rows : this.state.listData.concat(res.rows),
        refreshIcon: false,
      })
    } else {
      this.setState({
        refreshIcon: false,
        status: 'error'
      })
    }
  }

  // 下拉刷新当月变更计划
  refresh = () => {
    this.pageParams.pageNo = 1;
    this.reload = false;
    this.initPage();
  }

  // 刷新当月变更计划
  reloadPage = () => {
    this.pageParams.pageNo = 1;
    this.reload = true;
    this.initPage();
  }

  // 加载更多当月变更计划
  loadMore = () => {
    if (this.totalPage > this.pageParams.pageNo) {
      this.pageParams.pageNo++;
      this.reload = false;
      this.initPage();
    }
  }

  renderSearchWarp = () => {
    let { isQh, orderType } = this.pageParams
    return (
      <View style={styles.searchWrap}>
        <TextInput
          ref="orderKeywordsInput"
          style={[styles.searchInput, isQh != 'Y' ? { width: 300 * scale } : {}]}
          underlineColorAndroid='transparent'
          placeholder={"订单号/企业名称/商品"}
          placeholderTextColor="rgba(39, 39, 39, .5)"
          maxLength={30}
          returnKeyType={'search'}
          defaultValue={this.pageParams.searchKey}
          onChangeText={(txt) => { this.pageParams.searchKey = txt; }}
          onSubmitEditing={() => { this.refresh() }}
        />
        {isQh == 'Y' && !this.bidId ? <Button text={'一键下单'} width={78} height={34} onPress={() => {
          this.props.navigation.navigate('historyOrderList', {
            orderType,
            tCode: 'QH'
          })
        }} /> : null}
      </View>
    )
  }


  _filterBidid = (cParmas, cSelect) => {
    console.log('cParmas', cParmas);
    console.log('cSelect', cSelect);
    let reselt = false;
    if (cParmas.companyId && (cParmas.companyId != cSelect.companyId)) {
      reselt = true;
      ToastUtil.showWarning('客户不符合');
    } else if (cParmas.goodsId && cSelect.orderItemList && (cParmas.goodsId != cSelect.orderItemList[0].goodsId)) {
      reselt = true;
      ToastUtil.showWarning('商品不符合');
    } else if (cParmas.payType && (cParmas.payType != cSelect.payType)) {
      reselt = true;
      ToastUtil.showWarning('收款类型不符合');
    } else if (cParmas.payStyle && (cParmas.payStyle != cSelect.payStyle)) {
      reselt = true;
      ToastUtil.showWarning('收款方式不符合');
    } else if (cParmas.deliveryType && (cParmas.deliveryType != cSelect.deliveryType)) {
      reselt = true;
      ToastUtil.showWarning('交付方式不符合');
    } else if (cParmas.transportType && (cParmas.transportType != cSelect.transportType)) {
      reselt = true;
      ToastUtil.showWarning('运输方式不符合');
    } else if (cParmas.srcAddressId && (cParmas.srcAddressId != cSelect.srcAddressId)) {
      reselt = true;
      ToastUtil.showWarning('交货地不符合');
    }
    return reselt;
  }

  selectFrame = (index) => {
    let { listData } = this.state;
    let { tCode, sendData } = this.props.navigation.state.params;
    // if (this.bidId && this._filterBidid(sendData, listData[index])) {//转单交验(泉化)
    //   return false;
    // }
    listData.forEach((item, i) => {
      if (index == i) {
        item.selected = !item.selected;
        this.selectedFrame = item.selected ? item : {}
      } else {
        item.selected = false;
      }
    })
    this.setState(listData)
  }

  nextStep = async () => {
    let { longFrame, sendData } = this.props.navigation.state.params;
    let { companyId, payType, payStyle, deliveryType, transportType, orderItemList, srcAddressId } = this.selectedFrame || {};

    // 转单交验 (接口)
    // if (this.bidId) {
    //   let res = await HTTP.POST(API_GENERATE(API.LONG_CHECKOUT), { ubmpResourceBidDetailInfo: sendData, reqSearchOrder: { companyId, payType, payStyle, deliveryType, transportType, goodsId: orderItemList[0].goodsId, srcAddressId } });
    //   if (res != 1) return;
    // }


    if (this.selectedFrame && this.selectedFrame.orderId) {
      if (longFrame && longFrame.orderId != this.selectedFrame.orderId) {
        Alert.alert('提示', `更换框架将替换之前数据，请谨慎操作！`, [
          { text: '确认', onPress: () => { this.jumpPage() } },
          { text: '取消' },
        ]);
      } else {
        this.jumpPage()
      }
    } else {
      ToastUtil.showWarning('请选择框架')
    }
  }

  jumpPage = () => {
    let { tCode, orderType, periodType, bidId, tranReportType, goodsId, bidOrderId, isCustIntentionPlan,
      bidIntentionOrderList,
      bidOrderItemList,
      srcAddress,
      srcAddressId, bidOrderIds } = this.props.navigation.state.params;
    console.log('this.props.navigation.state.params-123', this.props.navigation.state.params)

    if (bidId) {   //走意向
      this.props.navigation.navigate('orderBaseTurnPage', {
        longOrderId: this.selectedFrame.orderId,
        tCode, orderType, periodType,
        longIframe: true,
        isGoodsId: goodsId,
        bidId,
        tranReportType,
        bidOrderId,
        isCustIntentionPlan,
        bidIntentionOrderList,
        bidOrderItemList,
        srcAddress,
        srcAddressId,
        bidOrderIds
      })
    } else {
      this.props.navigation.navigate('orderBasePage', {
        longOrderId: this.selectedFrame.orderId,
        tCode, orderType, periodType,
        longIframe: true
      })
    }

  }

  renderListItem = (data) => {
    let item = data.item
    return (
      <View style={{ paddingLeft: 12 * scale, paddingRight: 12 * scale, }}>
        <TouchableOpacity activeOpacity={.6} style={{ marginBottom: 20 * scale }} onPress={() => { this.selectFrame(data.index) }}>
          <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
            <View style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 6 * scale }}>
              <Image style={{ marginRight: 8 * scale }} source={item.selected ? checkOn : checkOff} />
              <Text>{item.orderId || '--'}</Text>
            </View>
            <Text style={{ fontSize: 13 * scale, opacity: .5 }}>{item.createTime || '--'}</Text>
          </View>

          <View style={{ paddingLeft: 12 * scale, paddingRight: 12 * scale, paddingTop: 15 * scale, paddingBottom: 3 * scale, backgroundColor: '#fff' }}>
            <View style={styles.rows}>
              <Text style={{ maxWidth: '70%', color: '#148CFB', fontSize: 13 * scale }}>{item.companyName || '--'}</Text>
              <Text style={{ opacity: .3 }}> | </Text>
              <Text style={{ maxWidth: '30%', color: '#148CFB', fontSize: 13 * scale }}>{item.staffName || '--'}</Text>
            </View>

            {item.orderItemList && item.orderItemList.length > 0 ? (
              item.orderItemList.map((goodsItem, index) => {
                let { text } = CURRENCY.getUnit(goodsItem.currency);
                return (
                  <View style={[{ flex: 1, paddingBottom: 12 * scale }, index == item.orderItemList.length - 1 ? null : { borderBottomColor: '#EFEFEF', borderBottomWidth: 1, borderStyle: 'solid' }]} key={index}>
                    <Text style={{ fontSize: 13 * scale, fontWeight: "bold", marginBottom: 12 * scale, marginTop: 12 * scale }} numberOfLines={1}>{goodsItem.goodsName}</Text>

                    <View style={styles.rows}>
                      <Text style={styles.fontStyle}>剩余量: {goodsItem.quantity || '--'}{goodsItem.uomName}</Text>
                      <Text style={{ opacity: .3 }}> | </Text>
                      <Text style={styles.fontStyle}>{goodsItem.priceType == '2' ? (goodsItem.price || '公式价') : `${goodsItem.price || '一口价'}`}{goodsItem.price ? text + '/' + goodsItem.uomName : ''}</Text>
                      <View style={[{ marginLeft: 6 * scale, height: 16 * scale, flexDirection: 'row', alignItems: 'center', paddingLeft: 2 * scale, paddingRight: 2 * scale, borderRadius: 2 * scale }, goodsItem.priceType == '2' ? { backgroundColor: 'rgba(250 , 69, 22, .1)' } : { backgroundColor: 'rgba(20, 140, 251, .1)' }]}>
                        <Text style={[{ fontSize: 11 * scale }, goodsItem.priceType == '2' ? { color: '#FA4516' } : { color: '#148CFB' }]}>{goodsItem.priceTypeName}</Text>
                      </View>
                    </View>
                    <View style={[styles.rows, { marginTop: 5 * scale }]}>
                      <Text style={[styles.fontStyle, { maxWidth: '100%' }]}>结算公式: {goodsItem.priceFormlaName || '--'}</Text>
                    </View>
                  </View>
                )
              })
            ) : null}
          </View>
        </TouchableOpacity >
      </View>
    )
  }

  render() {
    let { status, listData, refreshIcon } = this.state;
    let { priceFormlaId } = this.pageParams;
    return (
      <View style={styles.container}>
        {this.renderSearchWarp()}

        {
          status == 'data' ? (
            <View style={{ flex: 1 }}>
              <FlatList
                data={listData}
                renderItem={this.renderListItem}
                refreshing={refreshIcon}
                onRefresh={() => { this.refresh() }}
                onEndReachedThreshold={0.1}
                onEndReached={() => { this.loadMore() }}
              />
            </View>
          ) : null
        }
        {
          status == 'data' ? (
            <View style={styles.btnWarp}>
              <Button text={'下一步'} width={300} height={34} onPress={() => { this.nextStep() }} />
            </View>
          ) : null
        }

        {status == 'loading' ? (<PageStatusIndex status={status} emptyText="暂无记录" onErrorPress={this.reloadPage} />) : null}
        {status == 'empty' ? (
          <View style={styles.textBox}>
            <Image style={styles.imgStyle} source={require('../../../imgs/global/dealtWithEmpty.png')} />
            <Text style={[styles.textTip, styles.fontWeight]}>请检查转单与框架匹配条件是否吻合：</Text>
            <Text style={styles.textTip}>如：1. 企业名称 、2. 付款方式、3. 交付方式、4. 运输方式、5. 出库地址、6. 目的地{priceFormlaId ? '、7. 结算公式(针对:暂定价业务)' : ''}等</Text>
          </View>
        ) : null}
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5F5F5'
  },
  searchWrap: {
    width: '100%',
    height: 66 * scale,
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center',
  },
  searchInput: {
    borderWidth: 1,
    borderStyle: 'solid',
    borderRadius: 6 * scale,
    borderColor: '#EDEDED',
    backgroundColor: '#fff',
    textAlign: 'center',
    height: 36 * scale,
    width: 250 * scale,
    paddingLeft: 10 * scale,
    paddingRight: 10 * scale,
    paddingVertical: 0,
  },
  btnWarp: {
    height: 72 * scale,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-around',
  },
  textBox: { flex: 1, alignItems: 'center', justifyContent: 'center' },
  textTip: {
    fontSize: 13 * scale,
    width: 260 * scale,
    lineHeight: 20 * scale
  },
  fontWeight: {
    fontWeight: 'bold',
    marginBottom: 10 * scale
  },
  imgStyle: {
    marginBottom: 22 * scale,
    width: 140 * scale,
    height: 140 * scale
  },
  rows: { flexDirection: 'row', alignItems: 'center' },
  fontStyle: { maxWidth: '42%', fontSize: 13 * scale, opacity: .65 }
})